import React, {useEffect, useState} from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    CardHeader,
    IconButton,
    InputAdornment,
    Paper,
    Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField,
    Typography
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import {AttachMoney, Done, RestartAlt} from "@mui/icons-material";
import LoadingButton from "@mui/lab/LoadingButton";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import DialogTitle from "@mui/material/DialogTitle";

import {del, list, pay, save} from "../../api/finance/referrer";
import {formatMoney} from "../../utils/math";
import {confirm} from "../common/confirm";
import {alert} from "../common/alert";
import Dialog from "@mui/material/Dialog";
import {YYYYMMDD} from "../../utils/time";
import {DatePicker} from "@mui/x-date-pickers/DatePicker";

import dayjs from "dayjs";

const TemplateForm = Object.freeze({
    id: 0,
    schoolId: 0,
    name: '',
    signupCommission: 0,
    orderCommission: 0,
    ct: null,
});

function Referrer() {

    const [loading, setLoading] = useState(false);
    const [referrers, setReferrers] = useState([]);

    const [submitting, setSubmitting] = useState(false);
    const [form, setForm] = useState({...TemplateForm});

    const [payOpen, setPayOpen] = useState(false);
    const [toPay, setToPay] = useState(null);
    const [ot, setOt] = useState(dayjs().subtract(1, 'day').startOf('day'));

    function loadReferrers() {
        setLoading(true);
        list().then(data => {
            setReferrers(data);
            setLoading(false);
        })
    }

    useEffect(() => {
        loadReferrers();
    }, []);

    const handleInputChange = (event) => {
        const {name, value} = event.target;
        setForm({...form, [name]: value});
    };

    function handleSubmit(event) {
        event.preventDefault();

        const signup = parseInt(form.signupCommission);
        const order = parseInt(form.orderCommission);

        if (isNaN(signup) || isNaN(order)) {
            alert("佣金必须为数字", "error");
            return;
        }

        if (signup < 0 || order < 0) {
            alert("佣金不能为负数", "error");
            return;
        }

        if (order > 100) {
            alert("订单佣金不能大于 100%", "error");
            return;
        }

        (signup === 0 || order === 0 ?
            confirm("你将某项佣金设置为 0，是否继续提交？") : Promise.resolve(true))
            .then(choice => {
                if (choice) {
                    setSubmitting(true);
                    return save(form);
                } else {
                    return false;
                }
            })
            .then(data => {
                if (data) {
                    setForm({...TemplateForm});
                    loadReferrers()
                }
                setSubmitting(false);
            });
    }

    function deleteReferrer(e) {
        confirm(`将要删除推广人 【${e.name}】，确定吗？`)
            .then(choice => choice ? del(e.id) : Promise.resolve(false))
            .then(data => {
                if (data) {
                    loadReferrers()
                }
            });
    }

    return (
        <Box p={4} display="flex" gap={4} flexWrap="wrap" alignItems="flex-start">
            <Card raised sx={{padding: 2, boxSizing: 'border-box', width: '55%', minWidth: '480px'}}>
                <CardHeader title={
                    <Stack direction="row" alignItems="center" spacing={1}>
                        <Typography variant="h5">推广人</Typography>
                        {loading && <CircularProgress color="inherit" size={24}/>}
                    </Stack>
                }/>

                <CardContent>
                    <TableContainer component={Paper}>
                        <Table>
                            <TableHead>
                                <TableRow>
                                    <TableCell width={'30px'}>ID</TableCell>
                                    <TableCell>名称</TableCell>
                                    <TableCell width={'72px'} align={"center"}>注册佣金</TableCell>
                                    <TableCell width={'72px'} align={"center"}>订单佣金</TableCell>
                                    <TableCell width={'140px'} align={"center"}>创建时间</TableCell>
                                    <TableCell width={'110px'} align={"center"}>操作</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {referrers.map(e => (
                                    <TableRow key={e.id}>
                                        <TableCell component="th" scope="row">{e.id}</TableCell>
                                        <TableCell>{e.name}</TableCell>
                                        <TableCell align={'center'}>{formatMoney(e.signupCommission)} 元/人</TableCell>
                                        <TableCell align={'center'}>{e.orderCommission}%</TableCell>
                                        <TableCell align={'center'}>{e.ct}</TableCell>
                                        <TableCell align={'center'}>
                                            <IconButton size="small" onClick={() => {
                                                setToPay(e);
                                                setPayOpen(true)
                                            }}>
                                                <AttachMoney/>
                                            </IconButton>
                                            <IconButton size="small" onClick={() => setForm(e)}>
                                                <EditIcon/>
                                            </IconButton>
                                            <IconButton size="small" onClick={() => deleteReferrer(e)}>
                                                <DeleteIcon/>
                                            </IconButton>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                </CardContent>
            </Card>

            <Card raised sx={{padding: 2, boxSizing: 'border-box', flexGrow: 1, minWidth: '360px'}}>
                <CardHeader title='修改'/>
                <CardContent>
                    <form onSubmit={handleSubmit}>
                        <Stack spacing={4}>
                            <TextField
                                margin="normal" required fullWidth autoComplete="off"
                                label="注册佣金" name="signupCommission" value={form.signupCommission}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">分</InputAdornment>
                                }}
                                onChange={handleInputChange}
                            />
                            <TextField
                                margin="normal" required fullWidth autoComplete="off"
                                label="订单佣金" name="orderCommission" value={form.orderCommission}
                                InputProps={{
                                    endAdornment: <InputAdornment position="end">%</InputAdornment>
                                }}
                                onChange={handleInputChange}
                            />
                            <Stack direction="row" spacing={2}>
                                <Button
                                    variant="contained" color="primary" sx={{marginTop: "16px", mr: 2}}
                                    startIcon={<RestartAlt/>} onClick={() => setForm({...TemplateForm})}
                                >清空</Button>
                                <LoadingButton
                                    type="submit" variant="contained" color="primary"
                                    sx={{marginTop: "16px"}}
                                    disabled={submitting || form.id === 0}
                                    startIcon={<Done/>}
                                    loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                    loading={submitting}
                                >提交</LoadingButton>
                            </Stack>

                        </Stack>
                    </form>
                </CardContent>
            </Card>

            <Dialog open={payOpen} onClose={() => setPayOpen(false)}>
                <DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                    <Typography variant="title">佣金支付状态</Typography>
                </DialogTitle>

                <Stack p={2} spacing={2}>
                    <DatePicker format={YYYYMMDD} sx={{width: 160}}
                                label="日期" value={ot}
                                onChange={v => setOt(v)}/>
                    <Button variant="contained" color="primary"
                            onClick={() => {
                                const date = ot.format("YYYY-MM-DD");
                                confirm(`将推广人 【${toPay.name}】 在 【${date}】 之前的未支付佣金全部修改为已支付，确定吗？`)
                                    .then(choice => choice ? pay(toPay.id, date) : Promise.resolve(false))
                                    .then(data => {
                                        if (data) {
                                            alert("修改佣金支付状态为已支付成功");
                                            setPayOpen(false);
                                            loadReferrers()
                                        }
                                    });
                            }}>
                        设为已支付
                    </Button>
                </Stack>
            </Dialog>
        </Box>
    );
}

export default Referrer;
